package com.my.yyr.service.safty.impl;

import com.my.yyr.base.Constants;
import com.my.yyr.base.DataStatusEnum;
import com.my.yyr.dao.safty.UserDao;
import com.my.yyr.dto.UserDto;
import com.my.yyr.exception.BusinessException;
import com.my.yyr.model.Role;
import com.my.yyr.service.safty.UserService;
import com.my.yyr.until.Utils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    private final UserDao userDao;

    @Autowired
    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public Map<String, Object> getUserPage(UserDto userDto) {
        return Utils.getPage(userDto, () -> userDao.findUserList(userDto));
    }

    @Override
    public void addUser(UserDto userDto) {

        if (userDao.findUserId(userDto.getU_id())) {
            throw new BusinessException("账号已存在");
        }

        userDto.setU_pwd(Constants.DEFAULT_PASSWORD);
        userDto.setU_status(DataStatusEnum.未确定.getCode());
        userDao.insertNewUser(userDto);
    }

    @Override
    public boolean existsUserId(String userId) {
        return userDao.findUserId(userId);
    }

    @Override
    public void deleteUser(String... ids) {
        if(ids==null || ids.length==0){
            throw new BusinessException("没有需要删除的数据");
        }

        userDao.deleteUsers(ids,DataStatusEnum.未确定.getCode());
    }

    @Override
    public void updUser(UserDto userDto) {
        userDao.updateUser(userDto);
    }

    @Override
    public boolean updateStatus(@Param("uid") String uid,@Param("opr") String opr) {
        String status = null;
        switch (opr) {
            case "confirm":
                status = DataStatusEnum.已启用.getCode();
                break;
            case "unuse":
                status = DataStatusEnum.已禁用.getCode();
                break;
            case "reuse":
                status = DataStatusEnum.已启用.getCode();
                break;
            default: throw new BusinessException("非法状态操作!");
        }
        return userDao.updateUserStatus(uid,status)>0;
    }

    @Override
    public List<Role> getRoleList() {
        return userDao.findRoleList();
    }

    @Override
    public List<String> getUserRoleIdList(String uid) {
        return userDao.findUserRoleIdList(uid);
    }

    @Override
    public void confirmRoles(UserDto userDto) {
        userDao.deleteUserRoles(userDto.getU_id());
        if(userDto.getRoleIds()!=null&& userDto.getRoleIds().length>0){
            userDao.insertUserRoles(userDto.getU_id(),userDto.getRoleIds());
        }
    }


}
